package com.fengmi.order.service.impl;

import cn.hutool.json.JSONUtil;
import com.api.goods.GoodsApi;
import com.fengmi.aop.monitor.MonitorLog;
import com.fengmi.cart.entity.Cart;
import com.fengmi.goods.entity.MallGoodsSku;
import com.fengmi.interceptor.UserInfoInterceptor;
import com.fengmi.order.dto.OrderDTO;
import com.fengmi.order.entity.OmsOrder;
import com.fengmi.order.entity.OmsOrderItem;
import com.fengmi.order.mapper.OmsOrderItemMapper;
import com.fengmi.order.mapper.OmsOrderMapper;
import com.fengmi.order.service.IOmsOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengmi.utils.id.IdWorker;
import com.fengmi.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Result;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zhuxm
 * @since 2022-03-14
 */
@Service
@Slf4j
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements IOmsOrderService {

    @Autowired
    private GoodsApi goodsApi;

    @Autowired
    private OmsOrderItemMapper omsOrderItemMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private IdWorker idWorker;

    //接口幂等的问题：同样的请求数据，被重复处理多次
    @Override
//    @GlobalTransaction
    @MonitorLog(time = 2)  //性能监控日志增强
    public ResultVO save(OrderDTO orderDTO) {




//        log.debug("come in ");
        //从请求头中获取id，实现唯一性处理
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String bizId = request.getHeader("bizId");


        Boolean res = redisTemplate.boundValueOps(bizId).setIfAbsent("1");// setnx ${bizId} 1
        if(!res){
            log.debug("请不要重复提交,会导致接口....");
            return new ResultVO(false,"请不要重复提交");
        }


        if (orderDTO == null) {
            return new ResultVO(false,"非法参数");
        }


        if (orderDTO.getAddress() == null) {

            return new ResultVO(false,"非法参数");
        }

        if(orderDTO.getOrder() == null){

            return new ResultVO(false,"非法参数");
        }

        if (orderDTO.getCartList() == null ||orderDTO.getCartList().size() <=0) {
            return new ResultVO(false,"非法参数");
        }

        //判断库存
        List<Cart> cartList = orderDTO.getCartList();
        for (Cart cart : cartList) {
            if(cart.isChoose()){
                //获取sku信息
                MallGoodsSku sku = goodsApi.findSkuById(cart.getSkuId());
                if(sku.getSkuStock() < cart.getBuyNum()){
                    return new ResultVO(false,"库存不足");
                }
            }
        }

        //保存订单主表信息
        OmsOrder order = new OmsOrder();
        //配送信息
        order.setReceiverName(orderDTO.getAddress().getLocName());
        order.setReceiverPhone(orderDTO.getAddress().getLocTel());
        order.setReceiverDetailAddress(orderDTO.getAddress().getLocInfo());
        order.setDeliveryCompany(orderDTO.getOrder().getDeliveryCompany()); //物流公司

        //设置订单编号(定长、数字组成、唯一不能重复)  分布式id生成策略
        long orderSN = idWorker.nextId();
        order.setOrderSn(orderSN+"");


        //计算订单总金额
        double totalPrice = 0;
        for (Cart cart : orderDTO.getCartList()) {
           if(cart.isChoose()){
               totalPrice += ( cart.getBuyNum()*cart.getPrice());
           }
        }

        order.setTotalAmount(new BigDecimal(totalPrice));

        //设置订单状态订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);
        //设置用户id
        order.setMemberId(UserInfoInterceptor.getUserInfo().getUserId());
        //设置时间
        //拉链表
//        order.setCreateTime(new Date());
//        order.setModifyTime(new Date());
        this.baseMapper.insert(order);



        //保存订单明细
        for (Cart cart : orderDTO.getCartList()) {

            if(cart.isChoose()){

                OmsOrderItem item = new OmsOrderItem();

                item.setOrderSn(orderSN+"");
                item.setProductId(Long.parseLong(cart.getSkuId()));
                item.setProductPrice(new BigDecimal(cart.getPrice()));
                item.setProductQuantity(cart.getBuyNum());

                omsOrderItemMapper.insert(item);

                //预扣库存
                ResultVO result = goodsApi.kcc(cart.getSkuId(), cart.getBuyNum());

                if (!result.isSuccess()){
                    throw new RuntimeException("库存扣减失败");
                }


            }

        }



        //删除购物车
        List<Cart> unchooseList = orderDTO.getCartList().stream().filter(cart -> !cart.isChoose()).collect(Collectors.toList());

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps("menhu:cart");
        operations.put(UserInfoInterceptor.getUserInfo().getUserId(), JSONUtil.toJsonStr(unchooseList));


        try {
            Thread.sleep(2300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        return new ResultVO(true,"success",orderSN+"");
    }
}
